package is.glif.fenius.webui.topo;


import is.glif.fenius.webui.common.WebUIException;

import java.io.File;
import java.util.HashMap;

import org.apache.cxf.helpers.FileUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FileEdgeProvider implements EdgeProvider {
    private static Logger log = Logger.getLogger(FileEdgeProvider.class);
    private static FileEdgeProvider instance;
    public static FileEdgeProvider getInstance() {
        if (instance == null) {
            instance = new FileEdgeProvider();
        }
        return instance;
    }
    private FileEdgeProvider() {
        this.refresh();
    }
    
    private String directory = "./config/edges"; 
    private HashMap<String, Long> lastLoaded = new HashMap<String, Long>();
    private HashMap<String, String> fileContents = new HashMap<String, String>();

    public synchronized void refresh() {
        Long now = System.currentTimeMillis();
        File folder = new File(directory);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            File file = listOfFiles[i];
            if (file.isFile()) {
                String fileName = file.getName();
                Long modified = file.lastModified();
                Long last = lastLoaded.get(fileName);
                // log.debug("file: "+fileName+" last modified: "+modified+" last loaded: "+last);
                boolean reload = false;
                if (!lastLoaded.containsKey(fileName) || last < modified) {
                    reload = true;
                }
                if (reload) {
                    log.debug("reloading "+fileName);
                    String jsonString = FileUtils.getStringFromFile(file);
                    lastLoaded.put(fileName, now);
                    fileContents.put(fileName, jsonString);
                }
            }
        }
    }

    public JSONArray getEdges(String network, String group, String match) throws WebUIException {
        this.refresh();
        JSONArray result = new JSONArray();
        match = match.replace("*", "");
        try {
            for (String jsonString : fileContents.values()) {
                JSONArray tmp = new JSONArray(jsonString);
                for (int j  = 0; j < tmp.length(); j++) {
                    JSONObject obj = tmp.getJSONObject(j);
                    String thisNet = obj.getString("network");
                    String thisName = obj.getString("name");
                    JSONArray groups = obj.getJSONArray("groups");
                    if (thisNet.equals(network)) {
                        boolean found = false;
                        int k = 0;
                        while (!found && k < groups.length()) {
                            if (group.equals("") || groups.getString(k).equals(group)) {
                                found = true;
                            } else if ((match.equals("") || thisName.startsWith(match)) ) {
                                found = true;
                            } else {
                                k++;
                            }
                        }
                        if (found) {
                            result.put(obj);
                        }
                    }
                }
            }
        } catch (JSONException e) {
            log.error(e);
            throw new WebUIException("Internal error loading edges");
        }
        return result;
    }

}
